clear variables; clear global; clear mex; close all; fclose('all'); clc
%%% NOTE: this code relies on functions from the PsychToolBox package,
%%% please make sure it is installed

dbstop if error % for debugging: trigger a debug point when an error occurs

% setup directories
myDir = fileparts(mfilename('fullpath'));
cd(myDir);
cd data;                        dirs.data       = cd;
        cd samples;             dirs.samples    = cd;   % directory where     *.tsv files with sample data generated by the readme files should be placed
cd ..;  cd msgs;                dirs.msgs       = cd;   % directory where *_msg.tsv files with messages generated by the readme files should be placed
cd ..;
cd ..;  cd function_library;    dirs.funclib    = cd;
cd ..;  cd results;             dirs.out        = cd;
cd ..;
addpath(genpath(dirs.funclib));                 % add dirs to path


%%% get all trials, parse into subject and stimulus
[files,nfiles] = FileFromFolder(dirs.samples,[],'tsv');

% check we have matching msg files
for p=nfiles:-1:1
    files(p).msgname = [files(p).fname '_msg.tsv'];
    if ~exist(fullfile(dirs.msgs,files(p).msgname),'file')
        warning('No matching message file ''%s'' found for sample file ''%s''',files(p).msgname,files(p).name)
        files(p) = [];
    end
end


fid = fopen(fullfile(dirs.out,'validation_accuracy.xls'),'wt');
fprintf(fid,'subject\tacc L\tacc R\n');

for p=1:nfiles
    fprintf('%s\n',files(p).fname);
    
    % load msgs file
    msgs = loadMsgsTsv(fullfile(dirs.msgs,files(p).msgname));
    
    acc = regexp(msgs(:,2),'validation data quality Dev_L: (\d+\.\d+), Dev_R: (\d+\.\d+)','tokens');
    acc = cat(1,acc{:});
    acc = str2double(acc{1});

    % print to file
    fprintf(fid,'%s\t%.3f\t%.3f\n',files(p).fname,acc);
end
fclose(fid);

rmpath(genpath(dirs.funclib));                  % cleanup path
